package org.example.myleet.p599;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        List<String> result = new ArrayList<>();
        int minIndexSum = Integer.MAX_VALUE;
        Map<String, Integer> list1Index = new HashMap<>(list1.length);
        for (int i = 0; i < list1.length; ++i) {
            list1Index.put(list1[i], i);
        }
        int indexSum;
        for (int i = 0; i < list2.length; ++i) {
            Integer i1 = list1Index.get(list2[i]);
            if (null != i1) {
                if ((indexSum = i1 + i) < minIndexSum) {
                    result.clear();
                    minIndexSum = indexSum;
                }
                if (indexSum == minIndexSum) {
                    result.add(list2[i]);
                }
            }
        }
        return result.toArray(new String[0]);
    }
}
